package user

import (
	"context"

	loginRpc "gitee.com/liuxuezhan/ar-platform/rpc-client/loginClient/client"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/userServiceClient/userrpc"
	"github.com/zeromicro/go-zero/core/logc"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"

	agentClient "gitee.com/liuxuezhan/ar-platform/rpc-client/agentClient/client"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/userServiceClient/userservice"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserBatchUpdateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserBatchUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserBatchUpdateLogic {
	return &UserBatchUpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserBatchUpdateLogic) UserBatchUpdate(req *types.UserBatchUpdateRequest) (resp *types.UserBatchUpdateResponse, err error) {
	resp = &types.UserBatchUpdateResponse{}

	if req.Opt == "toInternalAgent" || req.Opt == "toExternalAgent" {
		convertType := int64(1)
		if req.Opt == "toExternalAgent" {
			convertType = 2
		}
		rpcReq := &agentClient.AgentTypeBatchConvertRequest{
			UserIds: req.UserIdList,
			Type:    convertType,
		}
		_, err := l.svcCtx.AgentRPC.BatchConvertType(l.ctx, rpcReq)
		if err != nil {
			return nil, err
		}
	} else {
		rpcReq := &userservice.UserBatchUpdateRequest{
			Opt:        req.Opt,
			UserIdList: req.UserIdList,
			GroupId:    req.GroupId,
		}
		// 拉黑时将用户状态设置为不可用，同时将其踢下线
		if req.GroupId == -1 && req.Opt == "black" {
			// 踢下线
			_, err := l.svcCtx.LoginRpc.Offline(l.ctx, &loginRpc.OfflineReq{
				UserIds: req.UserIdList,
				IsAdmin: false,
			})
			if err != nil {
				logc.Error(l.ctx, "logout err:", err)
			}
			for _, id := range req.UserIdList {
				_, err = l.svcCtx.UserServiceRPC.UserModifyStatus(l.ctx, &userrpc.UserModifyStatusRequest{
					UserId: int64(id),
					Status: 1, // 0 启用，1禁用
				})
				if err != nil {
					logc.Error(l.ctx, "update user status", err)
				}
			}
		}
		if req.Opt == "disable" {
			// 踢下线
			_, err := l.svcCtx.LoginRpc.Offline(l.ctx, &loginRpc.OfflineReq{
				UserIds: req.UserIdList,
				IsAdmin: false,
			})
			if err != nil {
				logc.Error(l.ctx, "logout err:", err)
			}
		}
		_, err = l.svcCtx.UserServiceRPC.UserBatchUpdate(l.ctx, rpcReq)
		if err != nil {
			return nil, err
		}
	}

	return resp, nil
}
